package bzk3.geometry;

import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;

import android.util.Log;
import br.odb.libstrip.VertexArrayManager;

public class GLESVertexArrayManager /*extends VertexArrayManager */{


	int capacity;
	private FloatBuffer colorBuffer;
	private int currentVertexPosition;
	private boolean init;
	private int length;
	private FloatBuffer vertexBuffer;

	public GLESVertexArrayManager() {
		super();
	}

	final public void draw(GL10 gl) {
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		gl.glColorPointer(4, GL10.GL_FLOAT, 0, colorBuffer);
		gl.glDrawArrays(GL10.GL_TRIANGLES, 0, currentVertexPosition / 3);
	}

	final public void flushToGLES() {
		
		vertexBuffer.position(0);
		colorBuffer.position(0);
	}

	final public void init(int numFaces) {
		Log.d("bzk3", "init VA manager with " + numFaces + " positions");
		ByteBuffer byteBuf;
		capacity = numFaces * ( ( 6 * ( 3 + 4) ) * 4 );
		byteBuf = ByteBuffer.allocateDirect( capacity );
		byteBuf.order(ByteOrder.nativeOrder());
		vertexBuffer = byteBuf.asFloatBuffer();
		byteBuf = ByteBuffer.allocateDirect( capacity );
		byteBuf.order(ByteOrder.nativeOrder());
		colorBuffer = byteBuf.asFloatBuffer();

		init = true;
		resetState();
	}

	final public void onFrameRenderingFinished() {
		resetState();
		//this.vertexBuffer.clear();
		//this.colorBuffer.clear();
		this.vertexBuffer.rewind();
		this.colorBuffer.rewind();
		length = 0;
	}

	final public void pushIntoFrameAsStatic(float[] fs, float[] fs2) {
		try {

			if (init && (length < capacity)) {

				vertexBuffer.put(fs);
				currentVertexPosition += fs.length;
				length += fs.length * 4;
				
				for ( int c = 0; c < ( fs.length / 3 ); ++c )
					colorBuffer.put(fs2);
			}
		} catch (BufferOverflowException e) {
			e.printStackTrace();
			Log.d("bzk3", "length: " + length + " capacity: " + capacity);
		}

	}

	final private void resetState() {
		currentVertexPosition = 0;
	}

	public void copyTo(GLESVertexArrayManager manager) {
		manager.vertexBuffer.put( this.vertexBuffer );
		manager.colorBuffer.put( this.colorBuffer );
		manager.currentVertexPosition = this.currentVertexPosition;
		manager.length = this.length;
		
	}
}
